package mb.view;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.net.URL;

public class AppToolBar extends JToolBar implements ActionListener {

  public static final	int	SELECT	=	1;
  public static final	int	BOX		  =	2;

	private static final String SELECT_IMAGE = "images/selectButton.gif";
  private static final String BOX_IMAGE		 = "images/boxButton.gif";

  private	JButton selectButton = new JButton(this.getImageIcon(SELECT_IMAGE));
  private	JButton boxButton 	 = new JButton(this.getImageIcon(BOX_IMAGE));

  private int selectedButton = SELECT;

  public AppToolBar() {
  	super();

    selectButton.setActionCommand("Select");
    selectButton.addActionListener(this);
  
    boxButton.setActionCommand("Box");
    boxButton.addActionListener(this);

    this.add(selectButton);
    this.add(boxButton);
  }

  public int getSelectedButton() {
    return selectedButton;
  }

  private void setSelectedButton(int aButton) {
    selectedButton = aButton;
    if (selectedButton == SELECT) {
      selectButton.setSelected(true);
      boxButton.setSelected(false);
    }
    else if (selectedButton == BOX) {
      boxButton.setSelected(true);
      selectButton.setSelected(false);
    }
  }

  public ImageIcon getImageIcon(String anImage) {
    // {+
    URL url = null;
    ImageIcon imageIcon = null;
    try {
    // +}
      url = this.getClass().getResource(anImage);
      imageIcon = new ImageIcon(url);
    // {+
    }
    catch (Exception e) {
      System.out.println(e.getMessage() + " // no URL");
    }
    // +}
    return imageIcon;
  }

  private int getCommand(String aCommand) {
    int	action = -1;
    if     (aCommand.equals("Select")) action = SELECT;
    else if(aCommand.equals("Box"))    action = BOX;
    return action;
  }

  public void actionPerformed(ActionEvent e) {
    String command = e.getActionCommand();
    switch (this.getCommand(command)) {
      case SELECT:  this.setSelectedButton(SELECT);
                    break;
      case BOX:     this.setSelectedButton(BOX);
                    break;
    }
  }
  
}
